//
//  AppointmentShangMenTwoViewController.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 10/25/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "AppointmentShangMenTwoViewController.h"

#import "OrderConfirmViewController.h"


@interface AppointmentShangMenTwoViewController ()
{
    UIScrollView * mScrollView;
    UITextView *  textView;
    UILabel * addressLB;
    UILabel * timeLB;
    UITextField * detailAddressTF;
    TimeView * timeView;
    
    NSString * day;
    NSString * hour;
    NSMutableArray * emplTimeArray;
    
    BMKLocationService * locService;
    BMKMapView * mapView;
    
    BMKGeoCodeSearch * searcher;
    
    CGFloat latitude;
    CGFloat longitude;
}

@end

@implementation AppointmentShangMenTwoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [mapView viewWillAppear];
    mapView.delegate = self;
    locService.delegate = self;
    searcher.delegate  = self;
    if (self.comeSuperVC){
        [locService startUserLocationService];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [mapView viewWillDisappear];
    mapView.delegate = nil;
    locService.delegate = nil;
    searcher.delegate = nil;
    _comeSuperVC = NO;

}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleLabel.text = @"下单";
    self.type = 1;
    emplTimeArray = [[NSMutableArray alloc] init];
    
    [self initViews];
    
//    //自定义时间筛选控件
//    timeView = [[TimeView alloc] initWithFrame:self.contentView.frame];
//    [timeView setSouceTime:1];  //1表示是到家
//    timeView.delegate  =self;
//    [self.view addSubview:timeView];
    
    [self getDingWeiInfo];  //获取定位信息
    
    
}

#pragma mark
#pragma mark UI布局
-(void)initViews
{
    mScrollView = [[UIScrollView alloc] initWithFrame:self.contentView.bounds];
    mScrollView.contentSize = CGSizeMake(320, 568-64);
    mScrollView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:mScrollView];
    
    UIImageView * timeIV = [UIImageView initImageViewRect:CGRectMake(20, 15, 280, 40) andImage:LOADIMAGE(@"inputtime@2x") andUserInteractionEnabled:YES];
    [mScrollView addSubview:timeIV];
    
    UIImageView * addressIV = [UIImageView initImageViewRect:CGRectMake(20, height_y(timeIV)+15, 280, 40) andImage:LOADIMAGE(@"inputadress@2x") andUserInteractionEnabled:YES];
    [mScrollView addSubview:addressIV];
    
    UIImageView * detailAddressIV = [UIImageView initImageViewRect:CGRectMake(20, height_y(addressIV)+15, 280, 40) andImage:LOADIMAGE(@"detailaddress@2x") andUserInteractionEnabled:YES];
    [mScrollView addSubview:detailAddressIV];
    
    timeLB = [UILabel initLabelText:@"请选择预约时间" andRect:CGRectMake(61,0,240-61,40) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:14.5] andTextColor:UIColorFromRGB(0x666666) andTextAlignment:NSTextAlignmentLeft];
    timeLB.userInteractionEnabled = YES;
    timeLB.backgroundColor = [UIColor clearColor];
    [timeIV addSubview:timeLB];
    
    addressLB = [UILabel initLabelText:@"请选择地址" andRect:CGRectMake(61,0,200,40) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:14.5] andTextColor:UIColorFromRGB(0x666666) andTextAlignment:NSTextAlignmentLeft];
    addressLB.userInteractionEnabled = YES;
    [addressIV addSubview:addressLB];
    
    detailAddressTF  = [[UITextField alloc] initWithFrame:CGRectMake(61, 0, 210, 40)];
    detailAddressTF.placeholder = @"请输入详细地址";
    detailAddressTF.font  =[UIFont systemFontOfSize:14.5];
    detailAddressTF.textColor = UIColorFromRGB(0x666666);
    detailAddressTF.delegate = self;
    detailAddressTF.backgroundColor = [UIColor clearColor];
    detailAddressTF.returnKeyType = UIReturnKeyDone;
    detailAddressTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    detailAddressTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [detailAddressIV addSubview:detailAddressTF];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseTime)];
    [timeLB addGestureRecognizer:tap];
    
    UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseAddress)];
    [addressLB addGestureRecognizer:tap2];
    
    
    UIView * footview = [UIView initViewRect:CGRectMake(0, self.view.frame.size.height-49, UI_SCREEN_WIDTH, 49) andBackGroudColor:[UIColor whiteColor]];
    [self.view addSubview:footview];
    
    UIView * line = [UIView initViewRect:CGRectMake(0, 0.5, UI_SCREEN_WIDTH, 0.5) andBackGroudColor:UIColorFromRGB(0xdcdcdc)];
    [footview addSubview:line];
    
    UIButton * suerOrChooseBtn = [UIButton initButton:CGRectMake(45,4.5, 230, 40) btnImage:LOADIMAGE(@"xiadan@2x") btnTitle:@"下单" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:16]];
    [suerOrChooseBtn addTarget:self action:@selector(suerOrchooseempl) forControlEvents:UIControlEventTouchUpInside];
    [footview addSubview:suerOrChooseBtn];
    
    //百度地图
    locService = [[BMKLocationService alloc]init];
    locService.delegate = self;
    
    CGFloat qheight = iPhone5?20:0;
    mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, height_y(detailAddressIV)+20+qheight, UI_SCREEN_WIDTH, 180)];
    [mapView setZoomLevel:17];
    
    [mScrollView addSubview:mapView];
    
    searcher = [[BMKGeoCodeSearch alloc]init];
    searcher.delegate = self;
 
//    [self getEmplTime];
}

#pragma mark
#pragma mark 选择下单时间
-(void)chooseTime
{
    ChooseEmplTimeViewController * cvc = [[ChooseEmplTimeViewController alloc] initWithYinPenInfoArray:nil];
    cvc.delegate = self;
    [self.navigationController pushViewController:cvc animated:YES];
//    timeView.yBuseDateArray =nil;
//    timeView.userDateArray = emplTimeArray;
//    [timeView setTheViewShow];
//    [detailAddressTF resignFirstResponder];
    
}

#pragma mark
#pragma mark 选择地址
-(void)chooseAddress
{
    [detailAddressTF resignFirstResponder];
    ChooseAddressViewController * chooseVC = [[ChooseAddressViewController alloc] init];
    chooseVC.delegate = self;
    [self.navigationController pushViewController: chooseVC animated:YES];
}

#pragma mark
#pragma mark 查看摄影师时间安排表
-(void)chickTimeBtnClick
{
    DDLOG_CURRENT_METHOD;
}

#pragma mark
#pragma mark 下单或选摄影师
-(void)suerOrchooseempl
{
    if([timeLB.text isEqualToString:@"请选择预约时间"]){
        [XDTools showTips:@"请选择预约时间" toView:self.view];
        return;
    }
    if ([addressLB.text isEqualToString:@"请选择地址"]){
        [XDTools showTips:@"请选择地址" toView:self.view];
        return;
    }
    if (!(IS_NOT_EMPTY(detailAddressTF.text))){
        [XDTools showTips:@"请输入详细地址" toView:self.view];
        return;
    }
    
    //值的存储

    
    //地址
    [XDTools sharedXDTools].adderss = [[NSString alloc] initWithFormat:@"%@%@",addressLB.text,detailAddressTF.text];
    //时间
    [XDTools sharedXDTools].time = timeLB.text;

    
    //用来提交的数据
//    [XDTools sharedXDTools].SceneID = self.SceneID;
//    [XDTools sharedXDTools].EmplID = self.empID;
//    [XDTools sharedXDTools].SeriesID = self.SeriesID;
    [XDTools sharedXDTools].CityID = BJcityID;
    

    
    
    if ([hour isEqualToString:@"上午"]){
        [XDTools sharedXDTools].ShootDate = [[NSString alloc] initWithFormat:@"%@ %@",day,@"AM"];
    }else if ([hour isEqualToString:@"下午"]){
        [XDTools sharedXDTools].ShootDate = [[NSString alloc] initWithFormat:@"%@ %@",day,@"PM"];
    }else{
        [XDTools sharedXDTools].ShootDate = [[NSString alloc] initWithFormat:@"%@ %@",day,hour];
    }
    
    [XDTools sharedXDTools].ShootAddr = [[NSString alloc] initWithFormat:@"%@%@",addressLB.text,detailAddressTF.text];
    

        //跳入订单确认页
        if(ISLOGING){
            
            [XDTools sharedXDTools].iphoneNumber = [[NSUserDefaults standardUserDefaults] valueForKey:kMY_USER_IPHONE];
  
            [XDTools sharedXDTools].CustomerID = [[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID];
            [self ChickOrder];
        }else{
            loginViewController * loginVC = [[loginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
        }
    
}

#pragma mark
#pragma mark UITextFiled Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark
#pragma mark TimeViewDelegate
-(void)chooseTimeWithDay:(NSString *)mDay hour:(NSString *)mHour second:(NSString *)mSecond
{
    timeLB.text = [NSString stringWithFormat:@"%@ %@",mDay,mHour];
    
    day = [[NSString alloc] initWithFormat:@"%@",mDay];
    hour = [[NSString alloc] initWithFormat:@"%@",mHour];
}

#pragma mark
#pragma mark ChooseEmplTimeViewController Delegate
-(void)chooseTheEmplTimeWithTime:(NSString *)mString amOrPm:(NSString *)aop name:(NSString *)mname
{
    timeLB.text = [NSString stringWithFormat:@"%@ %@",mString,mname];
    
    day = [[NSString alloc] initWithFormat:@"%@",mString];
    hour = [[NSString alloc] initWithFormat:@"%@",mname];
}

#pragma mark
#pragma mark ChooseAddressViewController Delegate
-(void)chooseBMKPoiInfoFromBaiDuMap:(BMKPoiInfo *)poi
{
    if (poi == nil){
        if ([addressLB.text isEqualToString:@"请选择地址"]){
            //发起反向地理编码检索
            CLLocationCoordinate2D coordinate;
            coordinate.longitude = longitude;
            coordinate.latitude = latitude;
            BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
            reverseGeoCodeSearchOption.reverseGeoPoint = coordinate;
            BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
            if(flag)
            {
                NSLog(@"反geo检索发送成功");
            }
            else
            {
                NSLog(@"反geo检索发送失败");
            }
        }
    }else{
        //        mapView.showsUserLocation =NO;
        
        latitude = poi.pt.latitude;
        longitude =poi.pt.longitude;
        
        detailAddressTF.text = poi.name;
        addressLB.text = poi.address;
        
        mapView.delegate = self;
        
        NSArray* array = [NSArray arrayWithArray:mapView.annotations];
        [mapView removeAnnotations:array];
        
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = poi.pt;
        item.title = poi.name;
        [mapView addAnnotation:item];
        
    }
}


#pragma mark
#pragma mark 定位
-(void)getDingWeiInfo
{
    if([XDTools sharedXDTools].latitude&&[XDTools sharedXDTools].longitude){
        [locService startUserLocationService];
        mapView.showsUserLocation = NO;//先关闭显示的定位图层
        mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
        mapView.showsUserLocation = YES;//显示定位图层
    }else{
        [XDTools showTips:@"请在隐私中打开定位服务" toView:self.view];
    }
}

#pragma mark
#pragma mark 地图定位+显示
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewWillStartLocatingUser:(BMKMapView *)mapView
{
	NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude&&longitude){
        [locService stopUserLocationService];
        [mapView updateLocationData:userLocation];
        
        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度
    }
    
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude&&longitude){
        [locService stopUserLocationService];
        [mapView updateLocationData:userLocation];
        
        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度
        
        [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
        
        //发起反向地理编码检索
        BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeoCodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
        BOOL flag = [searcher reverseGeoCode:reverseGeoCodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }
    }
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)mapViewDidStopLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}


//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        addressLB.text = result.address;
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}


#pragma mark
#pragma mark 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    DDLOG_CURRENT_METHOD;
    NSString *AnnotationViewID = @"annotationViewID";
	//根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
    BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
		((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
		((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
	annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
	annotationView.canShowCallout = YES;
    annotationView.draggable = NO;
    [self performSelector:@selector(changeCenter) withObject:self afterDelay:1.5f];
    [mapView setCenterCoordinate:annotation.coordinate animated:YES];
    
    return annotationView;
}

-(void)changeCenter
{
    CLLocationCoordinate2D cooreinate;
    cooreinate.latitude = latitude;
    cooreinate.longitude = longitude;
    [mapView setCenterCoordinate:cooreinate animated:YES];
    
}


#pragma mark
#pragma mark 获取摄影师时间
-(void)getEmplTime
{
    if (![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    ASIHTTPRequest * request = [XDTools postRequestWithDict:@{@"EmplID":[XDTools sharedXDTools].EmplID} API:API_getEmplTime];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            [emplTimeArray removeAllObjects];
            if (ARRAY_IS_NOT_EMPTY(tmpDict[@"data"][@"EmplUsedTime"])){
                [emplTimeArray addObjectsFromArray:tmpDict[@"data"][@"EmplUsedTime"]];
            }
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.view];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}

#pragma mark
#pragma mark 检查订单合法性
-(void)ChickOrder
{
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }

    NSDictionary * dict =@{@"SceneID":[XDTools sharedXDTools].SceneID,
                           @"CustomerID":[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID],
                           @"EmplID":[XDTools sharedXDTools].EmplID,
                           @"SeriesID":[XDTools sharedXDTools].SeriesID,
                           @"CityID":BJcityID,
                           @"ShootDate":@"",
                           @"ShootAddr":[[NSString alloc] initWithFormat:@"%@%@",addressLB.text,detailAddressTF.text],
                           @"ModeID":[XDTools sharedXDTools].ModeID,
                           @"Lat":[[NSString alloc] initWithFormat:@"%f",latitude],
                           @"Lng":[[NSString alloc] initWithFormat:@"%f",longitude]
                           };
    ASIHTTPRequest * request = [XDTools postRequestWithDict:dict API:API_checkOrder];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            OrderConfirmViewController * ovc = [[OrderConfirmViewController alloc] init];
            [self.navigationController pushViewController:ovc animated:YES];
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        mScrollView.hidden = YES;
        [XDTools hideProgress:self.view];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}

-(void)backPrePage
{
    [locService stopUserLocationService];
    mapView.showsUserLocation = NO;
    mapView.delegate = nil;
    locService.delegate = nil;
    searcher.delegate = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
